package com.king.first.app.sql;

import com.king.first.app.watermark.ClickSource;
import com.king.first.bean.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

public class Flink_SQL_01 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        SingleOutputStreamOperator<Event> eventStream = env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                            @Override
                            public long extractTimestamp(Event event, long l) {
                                return event.timestamp;
                            }
                        }));

        eventStream.map(Event::getTimestamp);

        // 创建表执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 将 dataStream 转换成 Table
        Table eventTable = tableEnv.fromDataStream(eventStream);

        // 直接写 SQL 进行转换
        Table sqlQuery = tableEnv.sqlQuery("select * from " + eventTable);

        Table result2 = eventTable.select($("user"), $("url"), $("timestamp")).where($("user").isEqual("aaa"));

        DataStream<Row> r1 = tableEnv.toDataStream(sqlQuery);
        DataStream<Row> r2 = tableEnv.toDataStream(result2);

//        r1.print();
        result2.execute().print();

        env.execute();
    }
}
